package hhm.android.main.history

import android.os.Bundle
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.trello.rxlifecycle4.RxLifecycle
import com.trello.rxlifecycle4.android.ActivityEvent
import hhm.android.library.datePicker.bean.DateParams
import hhm.android.library.utils.DialogUtils
import hhm.android.library.utils.GetDateListener
import hhm.android.library.utils.OnMultiClickListener
import hhm.android.main.OneFragmentInner
import siau.android.base.SBBaseActivity
import siau.android.base.getSureDialog
import siau.android.library.KeyString
import hhm.android.main.R
import hhm.android.main.databinding.ActivityHistoryListBinding
import siau.android.base.HttpHelper
import siau.android.base.SBApplication
import siau.android.base.enum.HeightClass
import siau.android.base.enum.WeightClass
import siau.android.http.model.*
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

class HistoryListActivity : SBBaseActivity() {

    lateinit var dataBinding: ActivityHistoryListBinding
    lateinit var adapter: HistoryListOutAdapter
    lateinit var viewModel: HistoryListViewModel
    private var group = ArrayList<ListHistoryModelGroup>()
    private var child = ArrayList<ListHistoryChildModel>()
    private var childId: Int = -1

    //1 weight    2 height
    private var pageType = 0
    var cla = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setTitleWhiteAndTextBlank()
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_history_list)
        initTitle(getString(R.string.history_list))
        viewModel = ViewModelProvider(this).get(HistoryListViewModel::class.java)
        dataBinding.viewModel = viewModel
        dataBinding.lifecycleOwner = this

        childId = intent.getIntExtra(KeyString.childId, -1)
        pageType = intent.getIntExtra(KeyString.type, -1)

        if (pageType == OneFragmentInner.PAGE_STATE_WEIGHT) {
            when (SBApplication.userData.weightUnit) {
                WeightClass.KG.msg -> cla = getString(R.string.class_kg)
                WeightClass.JIN.msg -> cla = getString(R.string.class_jin)
                WeightClass.LB.msg -> cla = getString(R.string.class_bang)
            }
        } else {
            when (SBApplication.userData.heightUnit) {
                HeightClass.CM.msg -> cla = getString(R.string.class_cm)
                HeightClass.FT.msg -> cla = getString(R.string.class_ft)
            }
        }

        val d = Date()
        val sdf = SimpleDateFormat("yyyy/MM")
        val string = sdf.format(d)
        val times = string.split("/")
        viewModel.year.value = times[0].toInt()
        viewModel.month.value = times[1].toInt()

        adapter = HistoryListOutAdapter(this, pageType, cla, group, object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
                DialogUtils.showDatePicBottomView(
                    this@HistoryListActivity,
                    object : GetDateListener {
                        override fun getDate(date: Date, string: String) {
                            val times = string.split("/")
                            viewModel.year.value = times[0].toInt()
                            viewModel.month.value = times[1].toInt()
                            showLoadingFragment(R.id.activity_history_list_fl)
                            viewModel.pageNo = 1
                            viewModel.selectList.value?.clear()
                            viewModel.selectListNum.value = 0
                            dataBinding.activityHistoryListRecycler.smoothScrollToPosition(0)
                            initData()
                        }
                    },
                    "yyyy/MM",
                    DateParams.TYPE_YEAR, DateParams.TYPE_MONTH,
                )
            }
        }, {
            if (viewModel.pageState.value == viewModel.PAGE_SELECT) {
                val model = it?.tag as ListHistoryChildModel
                if (model.select) {
                    model.select = false
                    viewModel.selectList.value!!.remove(model)
                    viewModel.selectListNum.value = viewModel.selectList.value!!.size
                } else {
                    model.select = true
                    viewModel.selectList.value!!.add(model)
                    viewModel.selectListNum.value = viewModel.selectList.value!!.size
                }
                if (viewModel.selectListNum.value == child.size) {
                    dataBinding.activityHistoryListAllSelectIv.setImageResource(R.mipmap.list_history_all_not_select)
                    dataBinding.activityHistoryListAllSelectTv.text = getString(R.string.all_not_select)
                    adapter.notifyDataSetChanged()
                } else {
                    dataBinding.activityHistoryListAllSelectIv.setImageResource(R.mipmap.list_history_all_select)
                    dataBinding.activityHistoryListAllSelectTv.text = getString(R.string.all_select)
                    adapter.notifyDataSetChanged()
                }
            }
        }, {
            if (viewModel.pageState.value == viewModel.PAGE_WATCH) {
                val model = it?.tag as ListHistoryChildModel
                showLoadingFragment(R.id.activity_history_list_fl)
                val l = ArrayList<Int>()
                l.add(model.id)
                val r = ListHistoryDeleteRequest(l, childId, pageType)
                HttpHelper().deleteHistory(r)?.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.STOP))?.subscribe({
                    viewModel.selectList.value?.clear()
                    viewModel.selectListNum.value = 0
                    dataBinding.activityHistoryListAllSelectIv.setImageResource(R.mipmap.list_history_all_select)
                    dataBinding.activityHistoryListAllSelectTv.text = getString(R.string.all_select)
                    val d = Date()
                    val sdf = SimpleDateFormat("yyyy/MM")
                    val string = sdf.format(d)
                    val times = string.split("/")
                    viewModel.year.value = times[0].toInt()
                    viewModel.month.value = times[1].toInt()
                    viewModel.pageNo = 1
                    dataBinding.activityHistoryListRecycler.smoothScrollToPosition(0)
                    initData()
                }, {
                    removeLoadingFragment()
                    showToast(it.message)
                })
            }
        })
        dataBinding.activityHistoryListRecycler.layoutManager = LinearLayoutManager(this)
        dataBinding.activityHistoryListRecycler.adapter = adapter

        dataBinding.activityHistoryListSmart.setFooterHeight(0f)
        dataBinding.activityHistoryListSmart.setOnRefreshListener {
            viewModel.pageNo = 1
            val d = Date()
            val sdf = SimpleDateFormat("yyyy/MM")
            val string = sdf.format(d)
            val times = string.split("/")
            viewModel.year.value = times[0].toInt()
            viewModel.month.value = times[1].toInt()
            viewModel.selectList.value?.clear()
            viewModel.selectListNum.value = 0
            dataBinding.activityHistoryListSmart.setNoMoreData(false)
            initData()
        }
        dataBinding.activityHistoryListSmart.setOnLoadMoreListener {
            viewModel.pageNo++
            initData()
        }

        viewModel.pageState.observe(this, {
            if (it == viewModel.PAGE_WATCH) {
                dataBinding.activityHistoryListAllSelectLl.visibility = View.GONE
                dataBinding.activityHistoryListSpace3.visibility = View.GONE
                dataBinding.topBackIv.setImageResource(R.mipmap.arrow_back)
                dataBinding.topTitle.text = getString(R.string.history_list)
                adapter.pageState = viewModel.PAGE_WATCH
                dataBinding.activityHistoryListDeleteIv.setImageResource(R.mipmap.select)
                dataBinding.activityHistoryListDeleteTv.text = getString(R.string.muti_select)
            } else if (it == viewModel.PAGE_SELECT) {
                dataBinding.activityHistoryListAllSelectLl.visibility = View.VISIBLE
                dataBinding.activityHistoryListSpace3.visibility = View.VISIBLE
                dataBinding.topBackIv.setImageResource(R.mipmap.x)
                adapter.pageState = viewModel.PAGE_SELECT
                dataBinding.activityHistoryListDeleteIv.setImageResource(R.mipmap.list_history_delete)
                dataBinding.activityHistoryListDeleteTv.text = getString(R.string.delete)
                changeTitle()
            }
            adapter.notifyDataSetChanged()
        })
        viewModel.selectListNum.observe(this, {
            if (viewModel.pageState.value == viewModel.PAGE_SELECT) {
                changeTitle()
            }
        })

        dataBinding.topBack.setOnClickListener {
            if (viewModel.pageState.value == viewModel.PAGE_WATCH) {
                finish()
            } else {
                viewModel.pageState.value = viewModel.PAGE_WATCH
                viewModel.selectList.value?.forEach {
                    it.select = false
                }
                viewModel.selectList.value!!.clear()
                viewModel.selectListNum.value = viewModel.selectList.value!!.size
                adapter.notifyDataSetChanged()
            }
        }

        dataBinding.activityHistoryListDelete.setOnClickListener {
            if (viewModel.pageState.value == viewModel.PAGE_WATCH) {
                viewModel.pageState.value = viewModel.PAGE_SELECT
            } else {
                if (viewModel.selectListNum.value!! > 0) {
                    getSureDialog(this, {
                        deleteData()
                    }, content = getString(R.string.sure_delete_data), showTitle = false)
                }
            }
        }

        dataBinding.activityHistoryListAllSelectLl.setOnClickListener {
            if (viewModel.selectListNum.value == child.size) {
                viewModel.selectList.value?.forEach {
                    it.select = false
                }
                viewModel.selectList.value!!.clear()
                viewModel.selectListNum.value = viewModel.selectList.value!!.size
                dataBinding.activityHistoryListAllSelectIv.setImageResource(R.mipmap.list_history_all_select)
                dataBinding.activityHistoryListAllSelectTv.text = getString(R.string.all_select)
                adapter.notifyDataSetChanged()
            } else {
                viewModel.selectList.value?.forEach {
                    it.select = false
                }
                viewModel.selectList.value!!.clear()
                for (i in 0 until child.size) {
                    viewModel.selectList.value!!.add(child[i])
                }
                viewModel.selectList.value?.forEach {
                    it.select = true
                }
                viewModel.selectListNum.value = viewModel.selectList.value!!.size
                dataBinding.activityHistoryListAllSelectIv.setImageResource(R.mipmap.list_history_all_not_select)
                dataBinding.activityHistoryListAllSelectTv.text = getString(R.string.all_not_select)
                adapter.notifyDataSetChanged()
            }
        }

        showLoadingFragment(R.id.activity_history_list_fl)
        initData()
    }

    private fun changeTitle() {
        dataBinding.topTitle.text = if (viewModel.selectListNum.value == 0) {
            "未选择"
        } else {
            "已选择 ${viewModel.selectListNum.value} 项"
        }
    }

    private fun initData() {
        if (viewModel.pageState.value == viewModel.PAGE_SELECT) {
            viewModel.pageState.value = viewModel.PAGE_WATCH
            viewModel.selectList.value?.clear()
            viewModel.selectListNum.value = 0
            dataBinding.activityHistoryListAllSelectIv.setImageResource(R.mipmap.list_history_all_select)
            dataBinding.activityHistoryListAllSelectTv.text = getString(R.string.all_select)
        }
        val r = ListHistoryRequest(viewModel.year.value!!, viewModel.month.value!!, childId, pageType, viewModel.pageNo, viewModel.pageSize)
        HttpHelper().listHistory(r)?.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.STOP))?.subscribe({
            if (it.size == 0) {
                if (viewModel.pageNo == 1) {
                    showNoDataView()
                    return@subscribe
                } else {
                    dataBinding.activityHistoryListSmart.finishLoadMoreWithNoMoreData()
                }
            } else {
                if (viewModel.pageNo == 1) {
                    group.clear()
                    child.clear()
                    dataBinding.activityHistoryListSmart.finishRefresh()
                } else {
                    dataBinding.activityHistoryListSmart.finishLoadMore()
                }
                it.forEach { m ->
                    val dateSplit = m.date.split("-")
                    val groupDate = dateSplit[0] + dateSplit[1]
                    if (group.size == 0) {
                        val groupModel = ListHistoryModelGroup()
                        groupModel.date = dateSplit[0] + "-" + dateSplit[1]
                        groupModel.modelList.add(m)
                        group.add(groupModel)
                    } else {
                        val lastGroupModel = group.last()
                        val lastGroupDateSplit = lastGroupModel.date.split("-")
                        val lastGroupDate = lastGroupDateSplit[0] + lastGroupDateSplit[1]
                        if (groupDate != lastGroupDate) {
                            val groupModel = ListHistoryModelGroup()
                            groupModel.date = dateSplit[0] + "-" + dateSplit[1]
                            groupModel.modelList.add(m)
                            group.add(groupModel)
                        } else {
                            lastGroupModel.modelList.add(m)
                        }
                    }
                    m.records.forEach { c ->
                        child.add(c)
                    }
                }
            }
            removeLoadingFragment()
            adapter.setGroups(group)
        }, {
            removeLoadingFragment()
            showToast(it.message)
        })
    }

    private fun deleteData() {
        showLoadingFragment(R.id.activity_history_list_fl)
        val l = ArrayList<Int>()
        viewModel.selectList.value?.forEach {
            l.add(it.id)
        }
        val r = ListHistoryDeleteRequest(l, childId, pageType)
        HttpHelper().deleteHistory(r)?.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.STOP))?.subscribe({
            viewModel.selectList.value?.clear()
            viewModel.selectListNum.value = 0
            dataBinding.activityHistoryListAllSelectIv.setImageResource(R.mipmap.list_history_all_select)
            dataBinding.activityHistoryListAllSelectTv.text = getString(R.string.all_select)
            val d = Date()
            val sdf = SimpleDateFormat("yyyy/MM")
            val string = sdf.format(d)
            val times = string.split("/")
            viewModel.year.value = times[0].toInt()
            viewModel.month.value = times[1].toInt()
            viewModel.pageNo = 1
            dataBinding.activityHistoryListRecycler.smoothScrollToPosition(0)
            initData()
        }, {
            removeLoadingFragment()
            showToast(it.message)
        })
    }
}